<template>
  <div class="wifi-settings-container">
    <el-card class="setting-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Connection /></el-icon>
          <span>店内WiFi设置</span>
        </div>
      </template>
      
      <div class="setting-content">
        <div class="description">
          <p>设置店内WiFi信息后，顾客下单之后可以看到WiFi名称和密码，方便顾客连接网络，提升用餐体验。</p>
        </div>
        
        <el-form
          ref="wifiFormRef"
          :model="wifiForm"
          :rules="wifiRules"
          label-position="top"
          class="setting-form"
        >
          <el-form-item label="WiFi名称" prop="wifiName">
            <el-input
              v-model="wifiForm.wifiName"
              placeholder="请输入WiFi网络名称"
              size="large"
              clearable
              maxlength="32"
              show-word-limit
            >
              <template #prefix>
                <el-icon><Connection /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="WiFi密码" prop="wifiPassword">
            <el-input
              v-model="wifiForm.wifiPassword"
              type="password"
              placeholder="请输入WiFi密码"
              size="large"
              clearable
              show-password
              maxlength="63"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        
        <div class="tips-section">
          <el-alert
            title="温馨提示"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <ul class="tips-list">
                <li>请确保WiFi名称和密码的准确性，避免顾客连接失败</li>
                <li>定期更新WiFi密码有助于维护网络安全</li>
                <li>如果WiFi无需密码，可以将密码字段留空</li>
                <li>设置的WiFi信息将在顾客下单后自动显示</li>
              </ul>
            </template>
          </el-alert>
        </div>
        
        <div class="action-buttons">
          <el-button size="large" @click="resetForm">重置</el-button>
          <el-button
            type="primary"
            size="large"
            :loading="saving"
            @click="saveWifiSettings"
          >
            保存设置
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { Connection, Lock } from '@element-plus/icons-vue';
import axios from 'axios';

const wifiFormRef = ref<FormInstance>()
const saving = ref(false)

const wifiForm = reactive({
  wifiName: '',
  wifiPassword: ''
})

const wifiRules = {
  wifiName: [
    { required: true, message: '请输入WiFi名称', trigger: 'blur' },
    { min: 1, max: 32, message: 'WiFi名称长度在1到32个字符', trigger: 'blur' }
  ],
  wifiPassword: [
    { min: 0, max: 63, message: 'WiFi密码长度不能超过63个字符', trigger: 'blur' }
  ]
}

// 发送请求到后端的函数
const sendWifiSettingsToBackend = async (wifiData: any) => {
  try {
    // 获取登录token
    const token = localStorage.getItem('token');
    const username = localStorage.getItem('username');
    
    const response = await axios.post('/systemSettings/add', {
      paramKey: wifiData.wifiName,
      paramValue: wifiData.wifiPassword,
      createPeople: username
    }, {
      headers: {
        'Content-Type': 'application/json',
        ...(token && { 'Authorization': `Bearer ${token}` })
      }
    })
    
    const { code, message, data } = response.data;

    if (code !== 200) {
      console.error('请求失败:', message)
      return {
        success: false,
        code: code,
        message: message || '保存失败'
      }
    } else {
      return {
        success: true,
        code: code,
        message: message || 'WiFi设置保存成功！',
        data: data || null
      }
    }
  } catch (error: any) {
    console.error('请求失败:', error)
    
    // 处理axios错误
    if (error.response) {
      const status = error.response.status
      let errorMessage = '请求失败'
      
      if (status === 403) {
        errorMessage = '权限不足，请重新登录'
      } else if (status === 401) {
        errorMessage = '登录已过期，请重新登录'
      } else if (status === 404) {
        errorMessage = '接口不存在'
      } else {
        errorMessage = `服务器错误：${status}`
      }
      
      return {
        success: false,
        message: errorMessage
      }
    } else if (error.request) {
      return {
        success: false,
        message: '网络连接失败，请检查网络'
      }
    } else {
      return {
        success: false,
        message: error.message || '未知错误'
      }
    }
  }
}

const saveWifiSettings = async () => {
  if (!wifiFormRef.value) return
  
  const valid = await wifiFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  try {
    // 显示确认框
    await ElMessageBox.confirm(
      '您确定向店内顾客提供免费WiFi吗？',
      '确认提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
    )
    
    // 用户点击确认后，开始保存操作
    saving.value = true
    
    // 发送请求到后端
    const result = await sendWifiSettingsToBackend(wifiForm);
    
    if (result?.success) {
      ElMessage.success(result.message)
      
      // 保存成功后清空表单内容
      wifiForm.wifiName = ''
      wifiForm.wifiPassword = ''
      
      // 清除表单验证状态
      if (wifiFormRef.value) {
        wifiFormRef.value.clearValidate()
      }
      
      // 可选：同时清除本地存储
      localStorage.removeItem('wifiSettings')
      
    } else {
      ElMessage.error(result?.message || '保存失败，请重试')
    }
    
  } catch (error) {
    // 用户点击取消或其他错误
    if (error === 'cancel') {
      // 用户点击取消，不做任何操作，保持表单内容
      ElMessage.info('已取消保存操作')
    } else {
      console.error('保存过程中发生错误:', error)
      ElMessage.error('保存过程中发生错误，请重试')
    }
  } finally {
    saving.value = false
  }
}

const resetForm = () => {
  if (wifiFormRef.value) {
    wifiFormRef.value.resetFields()
  }
}

onMounted(() => {
  // 从本地存储加载已保存的WiFi设置
  const savedSettings = localStorage.getItem('wifiSettings')
  if (savedSettings) {
    try {
      const parsedSettings = JSON.parse(savedSettings)
      Object.assign(wifiForm, parsedSettings)
    } catch (error) {
      console.error('加载保存的WiFi设置失败:', error)
    }
  }
})
</script>

<style scoped>
.wifi-settings-container {
  max-width: 800px;
  margin: 0 auto;
}

.setting-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.header-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 20px;
}

.setting-content {
  padding: 20px 0;
}

.description {
  background: #f0f9ff;
  border-left: 4px solid #409eff;
  padding: 16px 20px;
  margin-bottom: 30px;
  border-radius: 0 8px 8px 0;
}

.description p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.setting-form {
  margin-bottom: 30px;
}

.setting-form .el-form-item {
  margin-bottom: 24px;
}

.preview-section {
  margin-bottom: 30px;
}

.preview-section h4 {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 16px 0;
}

.wifi-preview {
  background: #fff;
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  padding: 20px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}

.wifi-icon {
  margin-right: 8px;
  font-size: 18px;
}

.wifi-info {
  padding-left: 26px;
}

.wifi-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.wifi-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #606266;
  width: 80px;
  flex-shrink: 0;
}

.value {
  color: #303133;
  font-weight: 500;
}

.no-wifi {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.no-wifi p {
  margin: 0;
}

.tips-section {
  margin-bottom: 30px;
}

.tips-list {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  line-height: 1.6;
}

.tips-list li {
  margin-bottom: 8px;
}

.tips-list li:last-child {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wifi-settings-container {
    padding: 0 16px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .wifi-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .label {
    width: auto;
    margin-bottom: 4px;
  }
}
</style> 